package com.zky.gulimall.product;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description TODO
 * @Author 张开源
 * @Date 2022/11/22 21:59
 * @Version 1.0
 **/
@Component
public class StrategyFactory implements ApplicationContextAware {

    private static Map<String, Strategy> testServiceMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        testServiceMap = new HashMap<>(16);
        // 通过applicationContext.getBeansOfType 动态获取接口的所有实现类
        Map<String, Strategy> map = applicationContext.getBeansOfType(Strategy.class);
        map.forEach((key, value) -> {
            testServiceMap.put(value.type(), value);
        });
    }


    public static Strategy getStrategy(String type) {
        Strategy testStrategy = testServiceMap.get(type);
        if (Objects.isNull(testStrategy)) {
            // 如果通过自定义编码没能找到具体实现类， 去执行默认的实现类代码
            return testServiceMap.get("default");
        } else
            return testStrategy;
    }
}
